package com.xtayfjpk.security;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import org.junit.Test;

public class KeyStoreTest {


	@Test
	public void testPKCS12() throws Exception {
		KeyStore keyStore = KeyStore.getInstance("pkcs12");
		//FileInputStream in = new FileInputStream("H:\\keystore\\zj.p12");
		FileInputStream in = new FileInputStream("D:\\imitation\\cert\\zhangjin\\zhangjin.p12");
		keyStore.load(in, "zhangjin".toCharArray());
		in.close();
		Enumeration<String> aliases = keyStore.aliases();
		while(aliases.hasMoreElements()) {
			String alias = aliases.nextElement();
			System.out.println("alias:" + alias);
			X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
			System.out.println(certificate);
			System.out.println(keyStore.getKey("zj", "zhangjin".toCharArray()));
		}
		
	}
	@Test
	public void testGitblitPKCS12() throws Exception {
		KeyStore keyStore = KeyStore.getInstance("pkcs12");
		//FileInputStream in = new FileInputStream("H:\\keystore\\zj.p12");
		FileInputStream in = new FileInputStream("D:\\installations\\gitblit-1.6.0\\data\\certs\\caKeyStore.p12");
		keyStore.load(in, "gitblit".toCharArray());
		in.close();
		Enumeration<String> aliases = keyStore.aliases();
		while(aliases.hasMoreElements()) {
			String alias = aliases.nextElement();
			System.out.println("alias:" + alias);
			X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
			System.out.println(certificate.getSigAlgName());
			System.out.println(keyStore.getKey(alias, "gitblit".toCharArray()));
		}
		
	}
	
	@Test
	public void testJKS() throws Exception {
		KeyStore keyStore = KeyStore.getInstance("jks");
		FileInputStream in = new FileInputStream("H:\\keystore\\test.keystore");
		keyStore.load(in, "123456".toCharArray());
		in.close();
		Enumeration<String> aliases = keyStore.aliases();
		while(aliases.hasMoreElements()) {
			String alias = aliases.nextElement();
			System.out.println("alias:" + alias);
			X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
			System.out.println(certificate);
		}
		
		PrivateKey privateKey = (PrivateKey) keyStore.getKey("mykey", "xtayfjpk".toCharArray());
		System.out.println(privateKey.getFormat());
		
		//keystore存储的证书有可能关联了私钥(PrivateKey)，也有可能没有关联，例如导入的受信息证书
		System.out.println(keyStore.getKey("zhangsan", "xtayfjpk".toCharArray()));
	}

}
